<template>
  <van-overlay :show="show" @click="show = false">
    <div class="cropper-wrapper" @click.stop>
      <div class="cropper-wrapper-main">
        <img :src="imgUrl" class="cropper-wrapper-img" ref="image" alt="" />
      </div>
      <div class="cropper-btns">
        <van-button class="cropper-btn" type="primary" @click="show = false">取消</van-button>
        <van-button class="cropper-btn" type="default" @click="sureSava">保存</van-button>
      </div>
    </div>
  </van-overlay>
</template>

<script setup lang="ts">
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import { ref } from 'vue'

const emit = defineEmits(['save'])

const show = ref(false)
const myCropper = ref()
const image = ref()
const imgUrl = ref()

async function createCropper(url: string) {
  if (!url) return
  imgUrl.value = url

  await Promise.resolve()

  if (!myCropper.value) {
    myCropper.value = new Cropper(image.value, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1
    })
    return
  }

  myCropper.value?.replace(url)
}

function open(url: string) {
  show.value = true
  createCropper(url)
}

/** 保存图片 */
function sureSava() {
  myCropper.value.getCroppedCanvas({ imageSmoothingQuality: 'high' }).toBlob(
    (blob: Blob) => {
      show.value = false
      emit('save', URL.createObjectURL(blob))
    },
    'image/jpeg',
    1
  )
}

defineExpose({
  open
})
</script>

<style scoped>
.cropper-wrapper {
  height: 100vh;
  width: 100%;
}
.cropper-wrapper-main {
  width: 100%;
  height: calc(100% - 100px);
}
.cropper-btns {
  height: 100px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  box-sizing: border-box;
}
.cropper-btn {
  width: 150px;
  background: #ffb463;
  border-color: #ffb463;
}
.cropper-btn:first-child {
  background: #fff;
  color: #333;
  border-color: #fff;
}
</style>
